package com.yougou.ui.login;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yougou.base.BaseViewModel;
import com.yougou.data.model.User;
import com.yougou.utils.UserDataManager;
import com.yougou.utils.UserManager;

public class LoginViewModel extends BaseViewModel {
    
    private MutableLiveData<User> loginResult = new MutableLiveData<>();
    private MutableLiveData<String> error = new MutableLiveData<>();
    
    public LiveData<User> getLoginResult() {
        return loginResult;
    }
    
    public LiveData<String> getError() {
        return error;
    }
    
    
    public void login(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            error.setValue("请输入用户名");
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            error.setValue("请输入密码");
            return;
        }
        
        if (password.length() < 6) {
            error.setValue("密码长度不能少于6位");
            return;
        }
        
        // 验证用户名和密码
        User user = UserDataManager.validateLogin(username, password);
        if (user == null) {
            error.setValue("用户名或密码错误");
            return;
        }
        
        // 保存登录状态
        UserManager.login(user);
        
        loginResult.setValue(user);
    }
    
    
    public void loginWithWechat() {
        simulateThirdPartyLogin("wechat");
    }
    
    
    public void loginWithQQ() {
        simulateThirdPartyLogin("qq");
    }
    
    
    private void simulateThirdPartyLogin(String platform) {
        String platformName = platform.equals("wechat") ? "微信" : "QQ";
        String thirdPartyId = platform + "_" + System.currentTimeMillis();
        String username = platformName + "用户_" + (System.currentTimeMillis() % 10000);
        
        User user = UserDataManager.thirdPartyLogin(platform, thirdPartyId, username);
        if (user != null) {
            UserManager.login(user);
            loginResult.setValue(user);
        } else {
            error.setValue(platformName + "登录失败，请重试");
        }
    }
}

